<?php


namespace common\helpers;


use yii\base\BaseObject;

/**
 * Notes: 分页类
 * User: Administrator
 * DateTime: 2021/4/2 17:10
 * Class Paginator
 * @package common\helpers
 */
class Paginator extends BaseObject
{
    // 分页对象
    private $_page;

    // 分页数据
    private $_list;

    // 页数
    private $_pageSize;

    // 默认页数
    private $_defaultPageSize = 10;

    public function setPage ($page)
    {
        $this->_page = $page;
    }

    public function getPage ()
    {
        return $this->_page;
    }

    public function setList ($list)
    {
        $this->_list = $list;
    }

    public function getList ()
    {
        return $this->_list;
    }

    public function setPageSize ($pageSize)
    {
        $this->_pageSize = $pageSize;
    }

    public function getPageSize ()
    {
        return $this->_pageSize;
    }

    /**
     * 实例
     */
    public static function getInstance ()
    {
        return new Paginator();
    }

    /**
     * 获取每页数量
     *
     * @return int
     */
    private function pageSize ()
    {
        if(is_null($this->_pageSize))
        {
            return $this->_defaultPageSize;
        }
        return $this->_pageSize;
    }

    /**
     * 分页
     */
    public function pagination ($query)
    {
        // 总条数
        $count = $query->count();
        // 响应全部的datatable的参数内容
        // 此内容由前端传递，为pageSize
        $pageSize = Requestor::post('length', $this->pageSize());

        // Yii自带分页类
        $page = new Pagination([
            'pageSize' => $pageSize,
            'totalCount' => $count
        ]);

        // offset, limit
        // offset 起始内容从前端传递
        $offset = Requestor::post('start', - 1);
        if(- 1 == $offset)
        {
            $offset = $page->offset;
        }
        $limit = $page->limit;
        // 数据列表
        $list = $query->offset($offset)->limit($limit)->all();

        // 设置
        $this->_page = $page;
        $this->_list = $list;

        return $this;
    }
}